<?php

namespace app\api\controller\v1;

use app\common\controller\Api;
use app\common\model\custom\Category;
use app\common\model\custom\Info;
use app\common\model\custom\Niu;
use app\common\model\ScoreLog;
use app\common\model\shop\Goods;
use app\common\utils\Utils;
use app\common\validate\custom\NiuValidate;
use think\Db;


/**
 * Token接口
 */
class MyCenter extends Api
{
    protected $noNeedLogin = ['systemInfo', 'category'];
    protected $noNeedRight = '*';
    protected $addressLogic = null;

    /**
     * 保存
     */
    public function myNiuSave() {
        $post = $this->request->post();
        $post['user_id'] = UID;
        (new NiuValidate())->goCheck();
        $niu = new Niu();
        if ($niu->where(['user_id'=> UID])->count() > 0) {
            $niu->isUpdate(true)->allowField(true)->save($post, ['user_id'=> UID]);
        } else {
            $niu->isUpdate(false)->allowField(true)->data($post)->save();
        }

        $this->success('保存成功');
    }

    /*我的牛场*/
    public function myNiu() {
        $niu = new Niu();
        $info = $niu->where(['user_id'=> UID])->find();

        $this->success('我的牛场', $info);
    }


    /**
     * 我的积分
     */
    public function myScore() {
        $scoreLog = new ScoreLog();
        $where['user_id'] = UID;
        $list = $scoreLog->where($where)->order('createtime desc')->paginate(20);
        list($sum, $cur) = [0, 0];
        if ($list->currentPage() == 1) {
            $sum = $scoreLog->where(['user_id' => UID, 'score' => ['gt', 0]])->sum('score');
            //当前积分
            $cur = $this->auth->score;
        }

        $returnData = [
            'cur' => $cur,
            'sum' => $sum,
            'total'     => $list->total(),         // 总记录数
            'current_page'       => $list->currentPage(),   // 当前页码
            'per_page'      => $list->listRows(),      // 每页记录数
            'data'      => $list->all()
        ];

        //累计总积分
        $this->success('积分列表', $returnData);
    }



    /**
     * 我的收藏
     */
    public function collect() {
        $goods_id = input('goods_id/d', 0);
        if (!$goods_id) {
            $this->error('参数错误');
        }
        $where['user_id'] = UID;
        $where['goods_id'] = $goods_id;

        $db = Db::name('shop_collect');
        if ($db->where($where)->count() > 0) {
            $this->error('已经收藏过');
        }

        $db->insert([
            'user_id' => UID,
            'goods_id' => $goods_id
        ]);

        $this->success('收藏成功');
    }

    /**
     * 我的收藏
     */
    public function myCollect() {
        $where['user_id'] = UID;
        $db = Db::name('shop_collect');
        $list = $db->where($where)->order('createtime desc')->paginate()
            ->each(function ($item, $key) {
                $goods_id = $item['goods_id'];
                $item['goods_info'] = Goods::get(function($query) use ($goods_id){
                    $query->where('id', $goods_id)->field(['content', 'pics'], true);
                });

                return $item;
            });

        $this->success('我的收藏', $list);
    }

    //取消收藏
    public function quitCollect() {
        $id = input('id/d', 0);
        Db::name('shop_collect')->where('id', $id)->delete();

        $this->success('取消成功');
    }
    /**
     * 系统信息
     */
    public function systemInfo() {
        //第一步 获取统计id 按天分组的id
        $info = new Info();
        $where['user_id'] = UID;
        $list = $info->where($where)
            ->order('createtime desc')
            ->paginate(20)
            ->each(function($item, $key) {
                $item->createtime_text = Utils::time_format($item['createtime'], 'H:i');
                $item->group_name = Utils::time_format($item['createtime'], 'Y-m-d');
            });

        $data = $list->all();
        $returnData = [];
        foreach ($data as $k => $v) {
            $group_name = $v['group_name'];
            if (isset($returnData[$group_name])) {
                array_push($returnData[$group_name], $v); //向后追加
            } else {
                $returnData[$group_name] = [$v];  //索引数组
            }
        }

        $lastData = [];
        foreach ($returnData as $k => $v) {
            $temp = [
                'date' => $k,
                'list' => $v
            ];

            array_push($lastData, $temp);
        }
        $resData = $list->toArray();
        $resData['data'] = $lastData;
        $this->success('分页列表', $resData);
    }


    /**
     * 我的足迹
     */
    public function getMyFoot() {
        $foot = Db::name('custom_foot');
        $list = $foot->where(['user_id' => UID])
            ->order('createtime desc')
            ->paginate(20)
            ->each(function($item, $key) {
                $item['createtime_text'] = Utils::time_format($item['createtime'], 'Y-m-d');
                $goods_info = Goods::get($item['goods_id']);
                if ($goods_info) {
                    $goods_info->hidden(['content', 'pics']);
                }

                $item['good_info'] = $goods_info;
                return $item;
            });

        $index = [];
        $res = [];  //  [ {key, goods}. {}, {} ]
        //按照时间进行重组
        foreach ($list as $k => $v) {
            $keys = array_keys($index, $v['createtime_text']);
            if ($keys) {
                //存在了
                $res_key = $keys[0]; //res的键位 索引
                array_push($res[$res_key]['goods'], $v);
            } else {
                //不存在
                $data['key'] = $v['createtime_text'];
                $data['goods'] = [$v]; //goods是一个新的数组
                array_push($res, $data);
                array_push($index, $v['createtime_text']);
            }
        }

        $resData = $list->toArray();
        $resData['data'] = $res;

        $this->success('我的足迹', $resData);
    }

    public function category() {
        $list = (new Category())->where(['switch' => 1])->select();

        $this->success('牛场分类', $list);
    }



}
